from datetime import datetime

import redis
import requests
import random
import time
import traceback  # 导入traceback模块
import jwt
from faker import Faker

fake = Faker()

count = 1
# API地址和基本信息
base_url = 'http://124.223.139.46:30001/api'
headers = {
    'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
}

timeout = 6 * 60 * 60

def is_jwt_format(token):
    parts = token.split('.')
    return len(parts) == 3

print(f"开始时间{datetime.now()}")
# 打开error.txt文件，准备写入错误信息
with open('error.txt', 'w', encoding='utf-8') as error_file:
    # 循环运行直到超时
    start_time = time.time()
    while time.time() - start_time < timeout:
        # 生成一个随机的名字
        first_name = fake.first_name()
        last_name = fake.last_name()
        try:
            # 生成234+10位数字随机手机号
            phone = '234' + f"{random.randint(1000000000, 9999999999)}"

            # 接口1：注册短信发送
            response = requests.post(
                f"{base_url}/users",
                headers=headers,
                data={'phone': phone}
            )
            response_data = response.json()

            if response.status_code == 200 and response_data.get('send') is True:
                # 接口2：注册
                response = requests.post(
                    f"{base_url}/user/verify",
                    headers=headers,
                    json={
                        "country": "Nigeria",
                        "first_name": first_name,
                        "invite_code": "",
                        "last_name": last_name,
                        "password": "qwe123",
                        "promo_code": "",
                        "type": "phone",
                        "value": phone,
                        "verification_code": "9999"
                    }
                )
                response_data = response.json()

                if response.status_code == 200:
                    access_token = response_data.get('auth', {}).get('access_token')
                    if is_jwt_format(access_token):
                        print(access_token)
                    else:
                        error_message = f"注册token非jwt,phone{phone},token{access_token}"
                        error_file.write(error_message + '\n')
                        error_file.flush()
                    user_id = response_data.get('id')
                    # 注册成功后，随机选择登录方式
                    dlfs = None
                    if random.choice(['password', 'verification_code']) == 'password':
                        # 密码登录
                        dlfs = "密码登录"
                        login_response = requests.post(
                            f"{base_url}/tokens",
                            headers=headers,
                            json={
                                "username": phone,
                                "password": "qwe123"
                            }
                        )
                    else:
                        dlfs = "短信验证码登录"
                        # 发送短信验证码
                        send_vc_response = requests.post(
                            f"{base_url}/tokens",
                            headers=headers,
                            json={
                                "type": "phone",
                                "value": phone,
                                "method": "verification_code"
                            }
                        )
                        send_vc_data = send_vc_response.json()
                        if send_vc_response.status_code == 200 and send_vc_data.get('sent') is True:
                            # 短信验证码登录
                            login_response = requests.post(
                                f"{base_url}/token/verify",
                                headers=headers,
                                json={
                                    "type": "phone",
                                    "value": phone,
                                    "verification_code": "9999"
                                }
                            )
                        else:
                            error_message = f"第{count}条数据，短信验证码发送失败，状态码{response.status_code}，响应信息{response.text}"
                            error_file.write(error_message + '\n')
                            error_file.flush()
                            continue  # 发送失败则跳过本次循环

                    # 检查登录是否成功
                    if login_response.status_code == 200:
                        login_data = login_response.json()
                        access_token = login_data.get('auth', {}).get('access_token')
                        if is_jwt_format(access_token):
                            print(access_token)
                        else:
                            error_message = f"登录token非jwt,phone{phone},token{access_token}"
                            error_file.write(error_message + '\n')
                            error_file.flush()

                        # 接口3：访问钱包
                        response = requests.get(
                            f"{base_url}/v2/user/wallet",
                            params={'user_id': user_id},
                            headers={'Authorization': f'Bearer {access_token}'}
                        )

                        if response.status_code != 200:
                            error_message = f"第{count}条数据，访问钱包失败，状态码{response.status_code}，响应信息{response.text}"
                            error_file.write(error_message + '\n')
                            error_file.flush()
                    else:
                        error_message = "登录失败"
                        print(error_message)
                        error_file.write(error_message + '\n')
                        error_file.flush()
                        continue  # 登录失败则跳过本次循环

                    print(f"第{count}条完成，登录方式{dlfs}")
                    count += 1
                    # print(phone)
                    time.sleep(10)
                else:
                    error_message = f"第{count}条数据，用户注册失败，状态码{response.status_code}，响应信息{response.text}"
                    print(error_message)
                    error_file.write(error_message + '\n')
                    error_file.flush()
                    continue  # 注册失败则跳过本次循环

            else:
                error_message = "接口1 - 短信发送失败"
                print(error_message)
                error_file.write(error_message + '\n')
                error_file.flush()
                continue  # 短信发送失败则跳过本次循环

        except Exception as e:
            print(f"异常时间{datetime.now()}")
            # 打印异常信息并写入到error.txt文件
            error_traceback = traceback.format_exc()
            print(error_traceback)
            error_file.write(f'第{count}条数据，出现异常：{error_traceback}\n')
            error_file.flush()
            count += 1
